#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import time
from typing import List, Optional

from db.DbExecutor import DbExecutor
from pojo import DevData

class DevDataOperator:
    """
    设备数据操作类
    """
    def __init__(self, query_db_path: str, create_insert_db_path: str):
        self.query_exec = DbExecutor(query_db_path)
        self.create_insert_exec = DbExecutor(create_insert_db_path)
        self.query_new_exec = DbExecutor(create_insert_db_path)
        logging.basicConfig(level=logging.DEBUG)
        self.logger = logging.getLogger(__name__)
    def query_dev_data(self, dev_id: int):
        """
        查询设备原始数据
        :param dev_id: 设备ID
        :return: 过滤后的设备数据
        """
        self.query_exec.connect()
        try:
            results = self.query_exec.query_dev_data(dev_id)
            self.logger.info(f"查询到设备原始数据：{len(results)}条")
            dev_data_list = [
                DevData(
                    data_id=row[6],
                    dev_id=row[7],
                    reg_id=row[8],
                    data_value=row[1],
                    data_time=row[0]
                )
                for row in results
            ]
            return dev_data_list
        finally:
            self.query_exec.close()
    def save_dev_data(self, dev_id: int, type: Optional[str], dev_data_list: List[DevData]):
        """
        读取设备数据并过滤异常数据
        :param dev_id: 设备ID
        :param type: 数据分类
        :param dev_data_list: 设备数据
        :return: 过滤后的设备数据
        """
        self.create_insert_exec.connect()
        self.create_insert_exec.create_dev_data_table(dev_id, type)
        try:
            i = 0
            for dev_data in dev_data_list:
                i = i + 1
                self.create_insert_exec.insert_dev_data(dev_id, type, dev_data)
                self.logger.debug(f"{time.time() * 1000}====>>插入第{i}条{type}数据：{dev_data}")
        finally:
            self.create_insert_exec.close()

    def query_mult_dimension_dev_data(self):
        """
        查询多维设备数据
        :return: 多维设备数据
        """
        self.query_new_exec.connect()
        try:
            results = self.query_new_exec.query_mult_dimension_dev_data()
            return  results
        finally:
            self.query_new_exec.close()